package org.linlinjava.litemall.db.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.linlinjava.litemall.db.dao.DevicesRecordMapper;
import org.linlinjava.litemall.db.dao.LitemallUserMapper;
import org.linlinjava.litemall.db.domain.DevicesRecord;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;

@Service
public class DevicesRecordService {


    @Autowired
    private DevicesRecordMapper recordMapper;

    @Autowired
    private LitemallUserMapper litemallUserMapper;

    public DevicesRecord getById(Integer id) {
        return recordMapper.selectById(id);
    }

    @Transactional
    public boolean save(DevicesRecord record) {
        // 自动填充创建时间（如果前端未传）
        if (record.getCreateTime() == null) {
            record.setCreateTime(LocalDateTime.now());
        }
        record.setStatus("0");

        //如果是上报直接增加余额
        if (record.getType().equals("report")){

            if (record.getPrice().compareTo(BigDecimal.ZERO) <= 0  && record.getPrice()!=null) {
                throw new RuntimeException("转账金额必须大于0");
            }

            litemallUserMapper.increaseOilQuantity(record.getFromId(),record.getPrice());
        }

        return recordMapper.insert(record) > 0;
    }

    @Transactional
    public boolean update(DevicesRecord record) {
        // 更新前校验存在性
        if (recordMapper.selectById(record.getId()) == null) {
            throw new RuntimeException("记录不存在");
        }
        return recordMapper.update(record) > 0;
    }

    @Transactional
    public boolean deleteById(Integer id) {
        // 逻辑删除（标记 deleted=1）
        DevicesRecord record = new DevicesRecord();
        record.setId(id);
        return recordMapper.update(record) > 0;
    }

    @Transactional
    public boolean completeRecord(Integer id) {
        DevicesRecord record = new DevicesRecord();
        record.setId(id);
        record.setStatus("0"); // 完成状态
        return recordMapper.update(record) > 0;
    }

    @Transactional
    public boolean failRecord(Integer id) {
        DevicesRecord record = new DevicesRecord();
        record.setId(id);
        record.setStatus("1"); // 失败状态
        return recordMapper.update(record) > 0;
    }

    public PageInfo<DevicesRecord> listByPage(int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<DevicesRecord> list = recordMapper.selectAll(); // 需在 Mapper 中添加 selectAll 方法
        return new PageInfo<>(list);
    }

    public List<DevicesRecord> listByStatus(String status) {
        // 示例：根据状态查询（需在 Mapper 中添加 selectByStatus 方法）
        return recordMapper.selectByStatus(status);
    }

}
